package pl.freetimetool.controller;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import pl.freetimetool.common.AccountRoles;
import pl.freetimetool.domain.AccountRole;
import pl.freetimetool.domain.Administrator;
import pl.freetimetool.exceptions.UserExistsException;
import pl.freetimetool.service.AccountService;

@Controller
public class AdministratorController {

	@Autowired
	AccountService accountService;

	@RequestMapping(value = "/administrator/add", method = RequestMethod.GET)
	public ModelAndView add() {
		final ModelAndView mav = new ModelAndView("/administrator/add");
		mav.addObject("administrator", new Administrator());
		return mav;
	}

	@RequestMapping(value = "/administrator/add", method = RequestMethod.POST)
	public ModelAndView add(@Valid final Administrator administrator, final BindingResult result) {
		final ModelAndView mav = new ModelAndView("administrator/add");
		if (!administrator.getPassword().equals(administrator.getRepeatedPassword())) {
			result.addError(new FieldError("administrator", "repeatedPassword", "notEqual"));
		}
		if (result.hasErrors()) {
			mav.addObject("administrator", administrator);
			return mav;
		}

		final List<AccountRole> ar = new ArrayList<AccountRole>();
		ar.add(new AccountRole(AccountRoles.ADMIN));

		try {
			this.accountService.registerAccount(administrator, ar);
		} catch (final UserExistsException e) {
		}

		mav.setViewName("redirect:/administrator/showDetails/" + administrator.getUsername());
		return mav;
	}
	@RequestMapping(value = "/administrator/showDetails/{username}", method = RequestMethod.GET)
	public ModelAndView details(@PathVariable("username") final String username) {
		final ModelAndView mav = new ModelAndView("administrator/showDetails");
		mav.addObject("administrator", this.accountService.getAccount(username));
		return mav;
	}

	@RequestMapping(value = "/administrator/adminPanel", method = RequestMethod.GET)
	public ModelAndView adminPanel() {
		final ModelAndView mav = new ModelAndView("administrator/adminPanel");

		final ArrayList<AccountRole> roles = new ArrayList<AccountRole>();
		roles.add(new AccountRole("ROLE_MANAGER"));

		mav.addObject("managers", this.accountService.listAccounts(roles));

		return mav;
	}

}
